package com.ysm.smfu.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClientOption;
import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.ysm.smfu.R;
import com.ysm.smfu.StatusBarCompat;
import com.ysm.smfu.activity.FoundActivity;
import com.ysm.smfu.activity.LocationActivity;
import com.ysm.smfu.activity.PayActivity;
import com.ysm.smfu.activity.SearchActivity;
import com.ysm.smfu.adapter.BannerPagerAdapter;
import com.ysm.smfu.adapter.HomeProductAdapter;
import com.ysm.smfu.adapter.MyPagerAdapter;
import com.ysm.smfu.area.Area;
import com.ysm.smfu.area.FileUtil;
import com.ysm.smfu.bean.AdListData;
import com.ysm.smfu.bean.City;
import com.ysm.smfu.bean.HomeProduct;
import com.ysm.smfu.bean.User;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.map.LocationTask;
import com.ysm.smfu.map.OnLocationGetListener;
import com.ysm.smfu.map.PositionEntity;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PopupWindowUtil;
import com.ysm.smfu.utils.StoreInfo;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ThreadUtils;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.CyclerViewPager;
import com.ysm.smfu.view.RefreshLayout;
import com.ysm.smfu.welcome.SharedConfig;
import com.ysm.smfu.zxing.activity.CaptureActivity;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import chatuidemo.activity.AddFriendsActivity;
import chatuidemo.activity.ZHSearchActivity;
import chatuidemo.db.DBManager;

/**
 * A simple {@link Fragment} subclass.
 * 首页
 */
public class HomeFragment extends BaseRefreshFragment<HomeProduct.Goods> implements View.OnClickListener {
    //猜你喜欢...     离我最近..
    private static final String LOCFAIL = "产品推荐";
    private static final String LOCSUCCESS = "产品推荐";
    //    title
    @BindView(R.id.fragment_search_module)
    AutoLinearLayout fragment_search_module;
    @BindView(R.id.home_listview)
    ListView homeListview;
    @BindView(R.id.home_hide_search_text)
    TextView home_hide_search_text;
    @BindView(R.id.sfewa)
    AutoRelativeLayout sfewa;
    @BindView(R.id.refresh)
    RefreshLayout refresh;
    @BindView(R.id.saoYiSao)
    ImageView saoYiSao;
    @BindView(R.id.mainActivity_topbar_img)
    ImageView mainActivity_topbar_img;

    //    头布局控件
    private CyclerViewPager home_spread_module;

    private MyReceiver myReceiver;
    private SharedPreferences sp;
    private String lon = "";
    private String lat = "";
    //    private BaseListAdapter adapter;//商户adapter
    private HomeProductAdapter adapter;//产品adapter
    //    当前城市，如果用户没有选择，则为空
    private String curCityId = "";
    private Area city;
    private String cityId = "";
    private String bdLoc = "";
    private String isBusiness = "";
    private Intent intent;
    private TextView distance_tome;

    private boolean isLocationFirst = true;
    private AMapLocationClientOption mLocationOption;
    private boolean isSetFirst = true;
    private String area_str;
    private ViewPager viewPager;
    private AutoLinearLayout ovels;

    boolean isFirst = false;
    String[] category_name1 = {"精品商城", "兑换券商城", "美食", "美容美发", "浴足", "ktv", "酒店", "聊天"};
    String[] category_name2 = {"兑换点", "加盟商店", "消费俱乐部", "生活在线", "私人定制", "电影", "游戏"};

    int[] category_ims1 = {R.drawable.sc, R.drawable.gwq, R.drawable.ms, R.drawable.mymf, R.drawable.yz,
            R.drawable.ktv, R.drawable.jd, R.drawable.lt};
    int[] category_ims2 = {R.drawable.dhd, R.drawable.jm, R.drawable.xfjlb,
            R.drawable.shzx, R.drawable.srdz, R.drawable.dy, R.drawable.yx};
    String[] category_id1 = {"-1", "-2", "1", "2", "4", "3", "5", "-3"};
    String[] category_id2 = {"8", "6", "0", "0", "0", "7", "0"};
    //    banner图集合
//    int[] drawerss = {R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four};
//    int[] drawers_noData = {R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four};//没有活动时显示
    int[] drawers_noData = {R.drawable.one};//测试页面
    String[] drawers;
    //    banner链接
    String[] links;
    String[] ids;
    private AutoLinearLayout ovelss;
    private ImageView[] indicators1;
    //    banner的指示点
    private ImageView[] indicators2;
    private BannerPagerAdapter bannerPagerAdapter;
    private MyConnectReceiver receiver;
    private NetworkInfo networkInfo;
    private String name;
    private SharedPreferences currShared;
    //    活动信息
    private String adData;
    private ImageView ad1;
    private ImageView ad2;
    private ImageView ad3;
    private ImageView ad4;
    private ImageView ad5;
    private LocationTask locationTask;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = UIUtils.inflate(R.layout.fragment_home_content);
        ButterKnife.bind(this, view);
        addHeadView();
        getConfig();
        getAdListData();
        registerLoc();
        registerForConnect();
        initRefresh(refresh, true, false);
        initTopBar();
        return view;
    }

    /**
     * 沉浸式状态栏实现
     */
    private void initTopBar() {
        StatusBarCompat.compat(getActivity(), getResources().getColor(R.color.green));
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        AutoLinearLayout.LayoutParams layoutParams = (AutoLinearLayout.LayoutParams) fragment_search_module.getLayoutParams();
        layoutParams.topMargin = StatusBarCompat.getStatusBarHeight(getContext());
        fragment_search_module.setLayoutParams(layoutParams);
//        }
    }

    /**
     * 获取本地保存的活动信息
     */
    private void getAdListData() {
        dealAdListData("");
        getAdListDataFromOnline();
    }

    /**
     * 从网络获取活动信息
     */
    private void getAdListDataFromOnline() {
        adData = sp.getString(SpKey.ADLISTDATA, "");
        if (TextUtils.isEmpty(adData))
            BaseProtocal.builder(false).getAdListData(new MyStringCallBack() {
                @Override
                public void onSuccess(String response) {
                    PrintUtil.printRespones("主页活动信息", response);
                    String state = JsonUtil.getState(response);
                    if (TextUtils.equals(state, "1")) {
                        adData = response;
                        dealAdListData(response);
                    }
                }

                @Override
                public void onFail(Exception e) {
                }
            });
        else
            dealAdListData(adData);
    }

    /**
     * 处理
     *
     * @param response
     */
    private void dealAdListData(String response) {
        if (TextUtils.isEmpty(response)) { //没有活动
            PrintUtil.printRespones("没有活动");
            bannerPagerAdapter = new BannerPagerAdapter(drawers_noData);
            home_spread_module.setAdapter(bannerPagerAdapter);
        } else { //有活动
            PrintUtil.printRespones("有活动");
            AdListData adListData = new Gson().fromJson(response, AdListData.class);
            List<AdListData.AdList> activityList = adListData.activityList;
            if (activityList != null && activityList.size() > 0) {
                drawers = new String[activityList.size()];
                links = new String[activityList.size()];
                ids = new String[activityList.size()];
                for (int i = 0; i < activityList.size(); i++) {
                    drawers[i] = activityList.get(i).banner_url;
                    links[i] = activityList.get(i).url;
                    ids[i] = activityList.get(i).id;
                }
                //banner模块
                bannerPagerAdapter = new BannerPagerAdapter(drawers, links, ids, this);
                home_spread_module.setAdapter(bannerPagerAdapter);
            }
        }
    }

    /**
     * 监听网络连接状态
     */
    private void registerForConnect() {
        IntentFilter intengFilter = new IntentFilter();
        intengFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        receiver = new MyConnectReceiver();
        getActivity().registerReceiver(receiver, intengFilter);
    }

    private class MyConnectReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeInfo = manager.getActiveNetworkInfo();
            if (networkInfo == null && activeInfo != null) {
                initLocation();
            } else if (networkInfo != null && activeInfo == null) {
                ToastUtils.showToast("网络断开，请检查网络状态");
            }
            networkInfo = activeInfo;
        }
    }

    /**
     * 为ListView添加头布局
     */
    private void addHeadView() {
        View headView = UIUtils.inflate(R.layout.fragment_home_head);
        initView(headView);
        /*增加头布局*/
        homeListview.addHeaderView(headView);
        adapter = new HomeProductAdapter(datas, homeListview, this);
        homeListview.setAdapter(adapter);
    }

    /**
     * 获取配置信息
     */
    private void getConfig() {
        if (sp == null)
            sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        name = sp.getString(SpKey.NAME, "");
        bdLoc = sp.getString(SpKey.BDLOC, "");
        lon = sp.getString(SpKey.LON, "");
        lat = sp.getString(SpKey.LAT, "");
        currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        PrintUtil.printRespones("获取保存到配置信息中的定位位置" + bdLoc);
         /*设置获取到的位置信息*/
        if (!TextUtils.isEmpty(bdLoc)) {
            setCity(bdLoc);
            distance_tome.setText(LOCSUCCESS);
        } else {
            setCity("定位中...");
            distance_tome.setText(LOCFAIL);
            locationTask();
        }
        getCityId();
        getBusinessId();
    }

    /**
     * 初始化头布局中控件
     *
     * @param headView
     */
    private void initView(View headView) {
        /*分类控件*/
        viewPager = (ViewPager) headView.findViewById(R.id.vp_category);
        ovels = (AutoLinearLayout) headView.findViewById(R.id.ovels);
//        分类模块共两页
        indicators1 = UIUtils.initIndicators(2, ovels, R.drawable.btn_circle_shape, R.drawable.btn_circle_shape_r);
         /*banner和指示点*/
        home_spread_module = (CyclerViewPager) headView.findViewById(R.id.home_spread_module);
        ovelss = (AutoLinearLayout) headView.findViewById(R.id.ovelss);
        /*支付模块*/
        distance_tome = (TextView) headView.findViewById(R.id.distance_tome);

//        推广模块指示点
        indicators2 = UIUtils.initIndicators(drawers_noData.length, ovelss, R.drawable.btn_circle_shape, R.drawable.btn_circle_shape_r);

        ad1 = (ImageView) headView.findViewById(R.id.ad1);
        ad2 = (ImageView) headView.findViewById(R.id.ad2);
        ad3 = (ImageView) headView.findViewById(R.id.ad3);
        ad4 = (ImageView) headView.findViewById(R.id.ad4);
        ad5 = (ImageView) headView.findViewById(R.id.ad5);

        initListener();
    }

    /**
     * 初始化控件点击
     */
    private void initListener() {
        // 分类模块
        final MyPagerAdapter adapter = new MyPagerAdapter(category_name1, category_name2, category_ims1, category_ims2, category_id1,
                category_id2, getActivity());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                changeOvel(position, false);
            }
        });
        // 推广活动模块
        home_spread_module.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                changeOvel(position, true);
            }
        });
//        点击事件
        home_spread_module.setOnClickListener(this);

//        搜索点击事件
        home_hide_search_text.setOnClickListener(this);
        sfewa.setOnClickListener(this);
        mainActivity_topbar_img.setOnClickListener(this);
//        扫一扫
        saoYiSao.setOnClickListener(this);
        ad1.setOnClickListener(this);
        ad2.setOnClickListener(this);
        ad3.setOnClickListener(this);
        ad4.setOnClickListener(this);
        ad5.setOnClickListener(this);
    }

    /**
     * 刷新/加载数据
     */
    @Override
    public void load(boolean isOnLoad) {
        if (isOnLoad)
            page++;
        isHasLoad = false;
        getGoodsInfoBySelect(cityId, curCityId, lon, lat);
//        刷新广告
        if (TextUtils.isEmpty(adData))
            getAdListData();
//        刷新定位
        if (TextUtils.isEmpty(bdLoc)) {
            initLocation();
        }
    }

    /**
     * 设置显示城市
     *
     * @param city
     */
    private void setCity(String city) {
        if (city.endsWith("市")) {
            city = city.substring(0, city.length() - 1);
        }
        home_hide_search_text.setText(city);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home_hide_search_text:
//                跳到位置界面
                UIUtils.startActivity(LocationActivity.class);
                break;
            case R.id.sfewa:
//                跳转到搜索页面
                UIUtils.startActivity(SearchActivity.class);
                break;
            case R.id.mainActivity_topbar_img:
//                显示popupWindow，来添加好友和扫一扫
                showPwForAddF();
                break;
            case R.id.saoYiSao:
//                if (!BaseProtocal.isGoLogin(true, getActivity()))
                //                付款---验证相机权限
                cameraTask();
                break;
            case R.id.ad1:
                break;
            case R.id.ad2:
                break;
            case R.id.ad3:
                break;
            case R.id.ad4:
                break;
            case R.id.ad5:
                break;
        }
    }

    /**
     * 显示popupWindow，来添加好友和扫一扫
     */
    private void showPwForAddF() {
        View popup = PopupWindowUtil.togglePopup("nainActivity", R.layout.popup_addf_ss_home,
                mainActivity_topbar_img, 5);
        if (isSetFirst)
            setPopupListenter(popup);
    }

    /**
     * 判断商户状态
     */
    private void judgeBusinessState() {
        isBusiness = currShared.getString(SpKey.IS_BUSINESS, "");
        if (TextUtils.equals(isBusiness, "01"))
            UIUtils.startActivity(PayActivity.class, "pay", 2);
        else
            chechShangHuState();
    }

    boolean isForCheckState;

    /**
     * 获取商户信息
     */
    private void chechShangHuState() {
        BaseProtocal.builder(true).chechShangHuState(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("检测商户状态", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String shState = jsonObject.optString("state");
                        if (TextUtils.equals(shState, "01")) {
                            currShared.edit().putString(SpKey.IS_BUSINESS, "01").commit();
                            isForCheckState = true;
                            getBusinessId();
                        } else if (TextUtils.equals(shState, "02")) {
                            showErrorDialog("商户已停用!");
                        } else
                            ToastUtils.showToast("您还不是商户,赶快去申请吧!");
                    } catch (JSONException e) {
                    }
                }
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    /**
     * 获取商户Id：进来时获取，如果不为01，则在点击收款时，再次获取
     */
    private void getBusinessId() {
        BaseProtocal.builder(true).getUserInfo(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    User userInfo = new Gson().fromJson(response, User.class);
                    StoreInfo.getInstance().store(currShared, userInfo);
                    DBManager.getInstance().saveContact2(userInfo.user);
                    if (isForCheckState) {
                        UIUtils.startActivity(PayActivity.class, "pay", 2);
                    }
                }
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    /**
     * 设置popupWindow中监听事件
     */
    private void setPopupListenter(View view) {
        isSetFirst = false;
        LinearLayout addFre = (LinearLayout) view.findViewById(R.id.popup_addFre);
        LinearLayout shouKuan = (LinearLayout) view.findViewById(R.id.popup_shouKuan);
        LinearLayout walleat = (LinearLayout) view.findViewById(R.id.popup_wallet);

        /**
         * 添加好友
         */
        addFre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BaseProtocal.isGoLogin(true, getActivity()))
                    UIUtils.startActivity(ZHSearchActivity.class);
                PopupWindowUtil.cancel("nainActivity", null);
            }
        });

        /**
         * 收款
         */
        shouKuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BaseProtocal.isGoLogin(true, getActivity()))
                    //               收款-- 检测商户状态
                    judgeBusinessState();
                PopupWindowUtil.cancel("nainActivity", null);
            }
        });

        /**
         * 我的钱包
         */
        walleat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BaseProtocal.isGoLogin(true, getActivity()))
                    UIUtils.startActivity(FoundActivity.class, "found", 14);
                //                UIUtils.startActivity(PayActivity.class, "pay", 3);
                PopupWindowUtil.cancel("nainActivity", null);
            }
        });
    }


    /**
     * 扫码成功后回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (intent == null) {
            intent = new Intent(getActivity(), PayActivity.class);
            intent.putExtra("pay", 1);
        }
        //处理扫描结果（在界面上显示）
        if (resultCode == getActivity().RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            String[] split = scanResult.split("\\?");
            PrintUtil.printRespones("扫码结果：" + split[0] + ">>>" + split[1]);
            dealScanResult(scanResult, split);
        }
    }

    /**
     * 付款
     */
    private void payMoneyAndJiFen(String dingdanInfo) {
        String[] split = dingdanInfo.split("#");
        intent.putExtra(SpKey.Pay_BUSSINESSID, split[0]);
        intent.putExtra(SpKey.MONEY, split[1]);
        intent.putExtra(SpKey.JIFEN, split[2]);
        if (split.length > 3)
            intent.putExtra(SpKey.REMARK, split[3]);
        startActivity(intent);
    }

    /**
     * 预付款
     */
    private void prePay(String businessId) {
        intent.putExtra(SpKey.MONEY, "");
        intent.putExtra(SpKey.JIFEN, "");
        intent.putExtra(SpKey.Pay_BUSSINESSID, businessId);
        startActivity(intent);
    }

    private void getCityId() {
        ThreadUtils.runOnBackThread(new Runnable() {
            @Override
            public void run() {
                if (area_str == null) {
                    String str = sp.getString(SpKey.AAASSEST, "");
                    if (!TextUtils.isEmpty(str))
                        area_str = str;
                    else {
                        area_str = FileUtil.readAssets(UIUtils.getContext(), "aa.json");
                        sp.edit().putString(SpKey.AAASSEST, area_str).commit();
                    }
                    city = new Gson().fromJson(area_str, Area.class);
                }
                if (!TextUtils.isEmpty(bdLoc)) {
                    if (TextUtils.isEmpty(curCityId)) {
                        curCityId = city.getIdByName(bdLoc);
//                保存定位的城市id到本地
                        sp.edit().putString(SpKey.LOCID, curCityId).commit();
                        getGoodsInfoBySelect(cityId, curCityId, lon, lat);
                    } else {
                        getGoodsInfoBySelect(cityId, curCityId, lon, lat);
                    }
                } else {
                    getGoodsInfoBySelect(cityId, curCityId, lon, lat);
                }
            }
        });
    }


    boolean isHasLoad;

    /**
     * 通过选择城市来获取最近商家
     * <p/>
     * <p/>
     * 目前展示产品  --修改涉及到HomeSearchResultBean，BaseListAdapter
     *
     * @param cityId
     * @param curCityId
     */
    private void getGoodsInfoBySelect(String cityId, String curCityId, String lon, String lat) {
        showProduct();
//            BaseProtocal.builder(false).getGoodsInfoBySelect(new MyStringCallBack() {
//                @Override
//                public void onSuccess(String response) {
//                    SysUtil.printRespones("页码:" + page "获取首页商家",  + response);
//                    String state = JsonUtil.getState(response);
//                    if (TextUtils.equals(state, "1")) {
//                        HomeSearchResultBean homeSearchResultBean = new Gson().fromJson(response, HomeSearchResultBean.class);
//                        List<HomeSearchResultBean.BusinessInfo> currBiList = homeSearchResultBean.biList;
////                    刷新加载时的处理数据
//                        setLoadData(currBiList);
//
//                        adapter.setDatas(datas);
//                        adapter.notifyDataSetChanged();
//                        isHasLoad = true;
//                    } else {
//                        onRefreshError();
//                    }
//                }
//
//                @Override
//                public void onFail(Exception e) {
//                    onRefreshError();
//                }
//            }, cityId, curCityId, lon, lat, page);
    }

    /**
     * 展示产品
     */
    private void showProduct() {
        BaseProtocal.builder(false).getHomeProduct(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("首页产品:" + response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    HomeProduct homeProduct = new Gson().fromJson(response, HomeProduct.class);
                    List<HomeProduct.Goods> goods = homeProduct.goods;
                    setLoadData(goods);

                    adapter.setDatas(datas);
                    isHasLoad = true;
                } else {
                    onRefreshError();
                }
            }

            @Override
            public void onFail(Exception e) {
                onRefreshError();
                PrintUtil.printRespones("获取首页产品异常");
            }
        }, page);
    }

    /**
     * 注册广播改变当前城市
     */
    private void registerLoc() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("loc");
        myReceiver = new MyReceiver();
        getActivity().registerReceiver(myReceiver, intentFilter);
    }

    //    切换指示点
    public void changeOvel(int position, boolean isScroll) {
        if (indicators1 != null && !isScroll)
            // 更改指示器图片
            for (int i = 0; i < indicators1.length; i++) {
                if (position != i)
                    indicators1[i].setBackgroundResource(R.drawable.btn_circle_shape);
                else
                    indicators1[i].setBackgroundResource(R.drawable.btn_circle_shape_r);
            }
        else if (indicators2 != null)
            // 更改指示器图片
            if (position == 1 || position == bannerPagerAdapter.getCount() + 1) {
                for (int i = 0; i < indicators2.length; i++) {
                    if (i == 0)
                        indicators2[i].setBackgroundResource(R.drawable.btn_circle_shape_r);
                    else
                        indicators2[i].setBackgroundResource(R.drawable.btn_circle_shape);
                }
            } else if (position == bannerPagerAdapter.getCount() || position == 0) {
                for (int i = 0; i < indicators2.length; i++) {
                    if (i == indicators2.length - 1)
                        indicators2[i].setBackgroundResource(R.drawable.btn_circle_shape_r);
                    else
                        indicators2[i].setBackgroundResource(R.drawable.btn_circle_shape);
                }
            } else {
                for (int i = 0; i < indicators2.length; i++) {
                    if (i + 1 == position)
                        indicators2[i].setBackgroundResource(R.drawable.btn_circle_shape_r);
                    else
                        indicators2[i].setBackgroundResource(R.drawable.btn_circle_shape);
                }
            }
    }


    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String name;
            City loc = (City) intent.getSerializableExtra(SpKey.LOC);
            if (loc.name.endsWith("市")) {
                name = loc.name.substring(0, loc.name.length() - 1);
            } else {
                name = loc.name;
            }
//            获取选择的城市ID
            cityId = loc.id;
            setCity(name);
////            将用户选择的城市id保存到本地
            sp.edit().putString(SpKey.SELECID, cityId).commit();
            sp.edit().putString(SpKey.SELECCITY, loc.name).commit();
//            城市改变，刷新数据
            isHasLoad = false;
            page = 1;
//            getGoodsInfoBySelect(cityId, curCityId, lon, lat);
        }
    }

    private void initLocation() {
        locationTask = LocationTask.getInstance();
        locationTask.setOnLocationGetListener(new OnLocationGetListener() {
            @Override
            public void onLocationGet(PositionEntity entity) {
                if (entity != null) {
                    locationTask.stopLocate();
                    //城市信息
                    String city2 = entity.city;
                    String address = entity.address;
                    sp.edit().putString(SpKey.ADDRESS_LOC, address).commit();
                    double latitude = entity.latitue;
                    double longitude = entity.longitude;

//                    保存城市信息到本地
                    sp.edit().putString(SpKey.BDLOC, city2).commit();
                    sp.edit().putString(SpKey.LAT, String.valueOf(latitude)).commit();
                    sp.edit().putString(SpKey.LON, String.valueOf(longitude)).commit();
                    if (city == null) {
                        if (area_str == null) {
                            if (sp == null)
                                sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
                            String str = sp.getString(SpKey.AAASSEST, "");
                            if (!TextUtils.isEmpty(str))
                                area_str = str;
                            else {
                                area_str = FileUtil.readAssets(UIUtils.getContext(), "aa.json");
                                sp.edit().putString(SpKey.AAASSEST, area_str).commit();
                            }
                        }
                        city = new Gson().fromJson(area_str, Area.class);
                    }
                    curCityId = city.getIdByName(city2);
                    bdLoc = city2;
                    lat = String.valueOf(latitude);
                    lon = String.valueOf(longitude);
//                保存定位的城市id到本地
                    sp.edit().putString(SpKey.LOCID, curCityId).commit();
                    if (city2.endsWith("市")) {
                        setCity(city2.substring(0, city2.length() - 1));
                    } else {
                        setCity(city2);
                    }
                    distance_tome.setText(LOCSUCCESS);
                    PrintUtil.printRespones("定位的城市信息：" + city + "---" + latitude + "---" + longitude);
                    page = 1;
                    getGoodsInfoBySelect(cityId, curCityId, lon, lat);

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    if (isLocationFirst) {
                        setCity("定位失败");
                        showErrorDialog("定位失败，请检查是否开启了网络和GPS或位置信息");
                        isLocationFirst = false;
                    }
                }
            }

            @Override
            public void onRegecodeGet(PositionEntity entity) {

            }
        });
        locationTask.startSingleLocate();
    }

    private static final int RC_CAMERA_PERM = 123;
    private static final int RC_LOCATION_PERM = 100;

    List<String> perms = new ArrayList<>();

    /**
     * 申请位置权限
     */
    public void locationTask() {
        AndPermission.with(this)
                .requestCode(RC_LOCATION_PERM)
                .permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(getActivity(), rationale);
                    }
                })
                .send();
    }

    @PermissionYes(RC_LOCATION_PERM)
    public void getLocationSuccess(List<String> grantedPermissions) {
        initLocation();
    }

    @PermissionNo(RC_LOCATION_PERM)
    public void getLocationFail(List<String> grantedPermissions) {
        if (AndPermission.hasAlwaysDeniedPermission(this, perms)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, RC_LOCATION_PERM).show();
        }
    }

    /**
     * 申请摄像头权限
     */
    public void cameraTask() {
        AndPermission.with(this)
                .requestCode(RC_CAMERA_PERM)
                .permission(Manifest.permission.CAMERA)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(getActivity(), rationale).show();
                    }
                })
                .send();
    }

    @PermissionYes(RC_CAMERA_PERM)
    public void getCameraSuccess(List<String> grantedPermissions) {
        Intent openCameraIntent = new Intent(getActivity(), CaptureActivity.class);
        startActivityForResult(openCameraIntent, 0);
    }

    @PermissionNo(RC_CAMERA_PERM)
    public void getCameraFail(List<String> grantedPermissions) {
        if (AndPermission.hasAlwaysDeniedPermission(getActivity(), grantedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, RC_CAMERA_PERM).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void showErrorDialog(String msg) {
        android.support.v7.app.AlertDialog dialog = new android.support.v7.app.AlertDialog.Builder(getActivity())
                .setMessage(msg).setNegativeButton("确定", null).create();
        dialog.show();
    }

    private void dealScanResult(String scanResult, String[] split) {
        if (TextUtils.equals(split[0], "type:addFriend") && !BaseProtocal.isGoLogin(true, getActivity())) {
            //  添加好友,传递用户Id
            UIUtils.startActivity(AddFriendsActivity.class, SpKey.USERID, split[1]);
        } else if (TextUtils.equals(split[0], "type:payMoney") || TextUtils.equals(split[0], "type:payPoints") && !BaseProtocal.isGoLogin(true, getActivity())) {
//              付款
            payMoneyAndJiFen(split[1]);
        } else if (TextUtils.equals(split[0], "type:payPre") && !BaseProtocal.isGoLogin(true, getActivity())) {
//                        预付款，自己输入金额
            prePay(split[1]);
            // 付款标志
        } else if (!TextUtils.equals(split[0], "type:addFriend") && !TextUtils.equals(split[0], "type:payMoney") && !TextUtils.equals(split[0], "type:payPre")) {
            Intent intent = new Intent(getActivity(), FoundActivity.class);
            intent.putExtra("found", 4);
            intent.putExtra(SpKey.INVITURL, scanResult);
            startActivity(intent);
        }
    }

    @Override
    public void afterOnResume() {
        super.afterOnResume();
        if (currShared != null) {
            String payBusinessId = currShared.getString(SpKey.Pay_BUSSINESSID, "");
            if (!TextUtils.isEmpty(payBusinessId)) {
                StoreInfo.getInstance().clearPayInfo(currShared);
            }
        }
    }

    @Override
    public void afterOnPause() {
        super.afterOnPause();
        isFirst = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (myReceiver != null)
            getActivity().unregisterReceiver(myReceiver);
        if (receiver != null)
            getActivity().unregisterReceiver(receiver);
    }
}
